//
//  YYRefreshControl.swift
//  YYWeibo
//
//  Created by strongwallyi on 16/1/6.
//  Copyright © 2016年 strongwallyi. All rights reserved.
//

import UIKit

enum YYRefreshControlState: Int {
    case Normal = 0         //默认状态
    case Pulling = 1        //下拉,松手即可刷新的状态
    case Refreshing = 2     //正在刷新的状态
}

//定义YYRefreshControlH的高度
private let YYRefreshControlH: CGFloat = 50

class YYRefreshControl: UIControl {
    
    //刷新控件之前的状态
//    var oldRefreshState: YYRefreshControlState = .Normal
    
    //当前刷新控件的状态
    var refreshState: YYRefreshControlState = .Normal {
        didSet{
            switch refreshState {
            case .Pulling:
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                messageLabel.text = "放开起飞"
            case .Normal:
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                messageLabel.text = "下拉刷新"
                arrowIcon.hidden = false
                indicatorView.stopAnimating()
                
                //当上一次是刷新状态,那么需要将菊花的状态栏收回去
                //oldValue 系统自带的记录上一次刷新的状态
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.5, animations: { () -> Void in
                        var contentInset = self.scrollView!.contentInset
                        contentInset.top = contentInset.top - YYRefreshControlH
                        self.scrollView?.contentInset = contentInset
                    })
                }
            case .Refreshing:
                //调整 contenInset的 top 值,让刷新获取数据的时候,菊花出现
            var contentInset = self.scrollView!.contentInset
            contentInset.top = contentInset.top + YYRefreshControlH
            self.scrollView?.contentInset = contentInset
            
            UIView.animateWithDuration(2, animations: { () -> Void in
                self.indicatorView.startAnimating()
                self.arrowIcon.hidden = true
                self.messageLabel.text = "正在加载"
            })
                //发送某个状态产生的事件
                sendActionsForControlEvents(.ValueChanged)
            }
            //记录状态,以便下一次在进行设置
//            oldRefreshState = refreshState
        }
    }
    
    weak var scrollView: UIScrollView?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.frame.size = CGSizeMake(SCREENW, YYRefreshControlH)
        self.frame.origin.y = -self.frame.height
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundColor = RandomColor()
        
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(indicatorView)
        
        // 添加约束
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-30)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrowIcon)
            make.leading.equalTo(arrowIcon.snp_trailing)
        }
        
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
    }
    
    //停止刷新
    func endRefreshing(){
        refreshState = .Normal
    }
    
    //当前控件将要移动到父控件的时候就会调用这个方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let scrollView = newSuperview as? UIScrollView {
            self.scrollView = scrollView
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
            
            //根据父控件的宽度设置自己的宽度
            self.frame.size.width = scrollView.frame.size.width
        }
    }
    
    //当前控件身上的 contentOffset 发生改变的时候就会回调这个方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //判断控件是否完全显示出来
        let contentInsetTop = scrollView!.contentInset.top
        
        //控件完全显示出来的条件
        let conditionValue = -contentInsetTop-YYRefreshControlH
        
        //如果当前是正在抓取的状态
        if scrollView!.dragging {
            if scrollView?.contentOffset.y <= conditionValue && refreshState == .Normal{
                refreshState = .Pulling
            }else if scrollView?.contentOffset.y > conditionValue && refreshState == .Pulling{
                refreshState = .Normal
            }
        }else{
            //用户松手,判断当前是否是松手就刷新的状态
            if refreshState == .Pulling {
                refreshState = .Refreshing
            }
        }
    }
    
    //懒加载箭头图标
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //懒加载当前状态的 label
    private lazy var messageLabel: UILabel = {
       let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "下拉刷新"
        return label
    }()
    
    //懒加载刷新中得状态控件
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView()
    
    //移除观察者
    deinit{
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    

}
